/*
   封装http请求
*/
// 部署时请求地址
// export const BASE_URL = "https://dantoublog.top/api";

// 测试时请求地址
export const BASE_URL = "http://127.0.0.1:8080";

export const httpGet = function(url, data = {}, header = {}, method = "GET", responseType = "text") {
	return httpRequest(url, data, method, header, responseType)
}

export const httpPost = function(url, data = {}, header = {}, method = "POST", responseType = "text") {
	return httpRequest(url, data, method, header, responseType)
}

// 获取二进制图片的数据流
export const httpGetArraybuffer = function(url, data = {}, method = "GET", header = {}, responseType = "arraybuffer") {
	return httpRequest(url, data, method, header, responseType)
}


export const httpRequest = function(url, data = {}, method, header = {}, responseType) {
	// console.log("url: ", url);
	// console.log("请求方式: " + method);
	// console.log("responseType: " + responseType);
	if (responseType === undefined) {
		responseType = "text"
	}

	let promise = new Promise(function(resolve, reject) {
		header["Cookie"] = uni.getStorageSync("cookies")
		header["token"] = uni.getStorageSync("token")
		console.log("header", header);
		uni.request({
			url: BASE_URL + url,
			data: data,
			method: method,
			header: header,
			responseType: responseType
		}).then(
			(res) => {
				// console.log(res);
				// 保存cookie
				if (res[1].header["Set-Cookie"] && res[1].header["Set-Cookie"] !== "") {
					// console.log("有cookies,保存");
					// 截取第一个;前面的字符串就是jsessionid
					uni.setStorageSync('cookies', res[1].header["Set-Cookie"].split(';')[0]);
				}

				if (res[1].statusCode == 200) {
					// console.log("封装请求成功");
					resolve(res[1])
				} else {
					// console.log("封装请求失败");
					reject(res[1])
				}
			}
		).catch(err => {
			console.error("请求报错,接口为:" + url);
			reject(err)
		})
	})
	return promise
}
